//
//  ComplainChildVC.m
//  运营管理系统
//
//  Created by 杨毅 on 17/2/20.
//  Copyright © 2017年 杨毅. All rights reserved.
//

#import "ComplainChildVC.h"

@interface ComplainChildVC ()
{
    NSDictionary *_prameter;
    NSInteger userID;
    NSInteger pageNumber;
    NSInteger sortypeState;//排列方式
    UIButton *_timeBtn;
    UIButton *_NumberBtn;

    
    NSDictionary *_infoDic;//通知带过来的参数
    NSString *_upImage;
    NSString *_WhetherName;//是否匿名
    UnusualBaseView *_UnusualBsView;
    UIImage *check;
    UIImage *uncheck;
}
@property (nonatomic,strong)UITableView *tableview;
@property (nonatomic,strong)NSMutableArray *dataSource;
@property (nonatomic,strong)UIView *addView;
@property (nonatomic,strong)AFHTTPSessionManager *manager;
@end

@implementation ComplainChildVC
- (AFHTTPSessionManager *)manager{
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}
- (NSString *)filePath{
    NSString *documentFilePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *filetPath = [documentFilePath stringByAppendingPathComponent:@"Log.txt"];
    return filetPath;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = UIColorFromRGB(0xffffff);
    _dataSource = [[NSMutableArray alloc]init];
    self.tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64) style:UITableViewStylePlain];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    self.tableview.rowHeight = 180;
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableview.backgroundColor = UIColorFromRGB(0xf0f0f0);
    UIView *heard = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, 40)];
    heard.backgroundColor = [UIColor whiteColor];
    UILabel *typeLab = [[UILabel alloc]initWithFrame:CGRectMake(12, 9, 80, 21)];
    typeLab.text = @"排列方式:";
    typeLab.textColor = UIColorFromRGB(0x4d4d4d);
    typeLab.textAlignment = NSTextAlignmentCenter;
    [heard addSubview:typeLab];
    check = [UIImage imageNamed:@"icon_image_correction_check_box_checked"];
    uncheck = [UIImage imageNamed:@"icon_image_correction_check_box_unchecked"];
    _timeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _timeBtn.frame = CGRectMake(97, 10, 80, 20);
    [_timeBtn setTitle:@"时间" forState:UIControlStateNormal];
    [_timeBtn setImage:check forState:UIControlStateNormal];
    _timeBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 60);
    _timeBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);/*上左下右*/
    [_timeBtn setTitleColor:UIColorFromRGB(0x4d4d4d) forState:UIControlStateNormal];
    
    _timeBtn.tag = 0;
    _timeBtn.selected = YES;
    [_timeBtn addTarget:self action:@selector(heardBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [heard addSubview:_timeBtn];
    
    
    _NumberBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _NumberBtn.frame = CGRectMake(CGRectGetMaxX(_timeBtn.frame)+10, 10, 80, 20);
    _NumberBtn.tag = 1;
    [_NumberBtn setTitle:@"赞同数" forState:UIControlStateNormal];
    [_NumberBtn setImage:uncheck forState:UIControlStateNormal];
    _NumberBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 60);
    _NumberBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);/*上左下右*/
    [_NumberBtn setTitleColor:UIColorFromRGB(0x4d4d4d) forState:UIControlStateNormal];
    [_NumberBtn addTarget:self action:@selector(heardBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [heard addSubview:_NumberBtn];
    
    
    [self.tableview setTableHeaderView:heard];
    [self.view addSubview:self.tableview];
    
    
    
    [self.tableview registerNib:[UINib nibWithNibName:@"SuggesOrComplainCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    self.addView = [[UIView alloc]initWithFrame:CGRectMake(kSCREEN_WIDTH-70, kSCREEN_HEIGHT-64, 50, 50)];
    self.addView.layer.cornerRadius = 25;
    self.addView.backgroundColor = UIColorFromRGB(0x0093d5);
    self.addView.layer.shadowOpacity = 2.0;
    self.addView.layer.shadowOffset = CGSizeMake(0, 0);
    self.addView.layer.shadowColor = UIColorFromRGB(0x000000).CGColor;
    [self.view addSubview:self.addView];
    
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addBtn.frame = CGRectMake(0, 0, 50, 50);

    [addBtn setTitle:@"＋" forState:UIControlStateNormal];
    addBtn.titleLabel.font = [UIFont systemFontOfSize:30.0];
    [addBtn addTarget:self action:@selector(AddSuggestion) forControlEvents:UIControlEventTouchUpInside];
    [self.addView addSubview:addBtn];
    
    sortypeState = _timeBtn.tag;
    NSDictionary *userDic = [NSDictionary dictionaryWithContentsOfFile:[self filePath]];
    userID =[[userDic objectForKey:@"userid"]integerValue];
    _prameter = @{@"userId":[NSString stringWithFormat:@"%ld",userID],@"sortType":@0,@"suggestionState":@2,@"pageNum":@0};
    [self ListNetworking];
    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [_dataSource removeAllObjects];
        pageNumber = 0;
        _prameter = @{@"userId":[NSString stringWithFormat:@"%ld",userID],@"sortType":[NSString stringWithFormat:@"%ld",sortypeState],@"suggestionState":@2,@"pageNum":[NSString stringWithFormat:@"%ld",pageNumber]};
        [self ListNetworking];
    }];

        self.tableview.mj_footer = [MJRefreshBackFooter footerWithRefreshingBlock:^{
            pageNumber = pageNumber + 1;
            _prameter = @{@"userId":[NSString stringWithFormat:@"%ld",userID],@"sortType":[NSString stringWithFormat:@"%ld",sortypeState],@"suggestionState":@2,@"pageNum":[NSString stringWithFormat:@"%ld",pageNumber]};
            [self ListNetworking];
        }];
    

}
- (void)sugBtnClick:(UIButton *)sender RowData:(NSDictionary *)rowDataDictionary{
    _infoDic = rowDataDictionary;
    
    //为了点赞成功还保持在原来的cell上 选用指定cell刷新 改变当前的原数据
    
    SugAndComBeanListModel *model = _dataSource[[_infoDic[@"row"]integerValue]];
    model.supportNum = [_infoDic[@"supprotNum"]integerValue];
    if ([_infoDic[@"type"] isEqualToString:@"cut"]) {
        model.supportState = [_infoDic[@"supprotState"]integerValue]-1;
        
    }else{
        model.supportState = [_infoDic[@"supprotState"]integerValue]+1;
        
    }
    NSIndexPath *indexPathA = [NSIndexPath indexPathForRow:[_infoDic[@"row"]integerValue] inSection:0]; //刷新第0段第2行
    [self.tableview reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathA,nil] withRowAnimation:UITableViewRowAnimationNone];
}
- (void)EndRrefresh{
    [self.tableview.mj_header endRefreshing];
    [self.tableview.mj_footer endRefreshing];
}
- (void)heardBtnClick:(UIButton *)sender{
    
    sortypeState = sender.tag;
    [self.tableview.mj_header beginRefreshing];
    _timeBtn.selected = NO;
    _NumberBtn.selected = NO;
    sender.selected = YES;
    if (sender.tag == 1) {
        [_NumberBtn setImage:check forState:UIControlStateNormal];
        [_timeBtn setImage:uncheck forState:UIControlStateNormal];
    }else{
        [_NumberBtn setImage:uncheck forState:UIControlStateNormal];
        [_timeBtn setImage:check forState:UIControlStateNormal];
    }
}
- (void)ListNetworking{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"加载中...";
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    self.manager.requestSerializer.timeoutInterval = 15;
    [_manager POST:SuggesAndCompListURL parameters:_prameter progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self EndRrefresh];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        SugAndComDataModel *datamodel = [[SugAndComDataModel alloc]initWithDictionary:dic[@"data"] error:nil];
        for (SugAndComBeanListModel *listModel in datamodel.beanList) {
            
            [_dataSource addObject:listModel];
        }
        if ([dic[@"status"]integerValue] == 1) {
            
            if (_dataSource.count == 0) {
                
                _UnusualBsView = [[UnusualBaseView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64) UnusualState:NotingDataStatus AndUnusualTitle:@"当前没有数据"];
                _UnusualBsView.delegate = self;
                [self.view insertSubview:_UnusualBsView belowSubview:self.addView];
            }else{
                
            }
            
        }else{
            _UnusualBsView = [[UnusualBaseView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64) UnusualState:ObtainDataFalStatus AndUnusualTitle:@"当前没有数据"];
            _UnusualBsView.delegate = self;
            [self.view insertSubview:_UnusualBsView belowSubview:self.addView];
        }
        [self.tableview reloadData];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self EndRrefresh];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        NSInteger status = responses.statusCode;
        if (status >= 500 ) {
            _UnusualBsView = [[UnusualBaseView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64) UnusualState:ServerQuestionStatus AndUnusualTitle:@"不好...服务器出错"];
            _UnusualBsView.delegate = self;
            [self.view insertSubview:_UnusualBsView belowSubview:self.addView];
        }else if (status == 404) {
            _UnusualBsView = [[UnusualBaseView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64) UnusualState:404 AndUnusualTitle:@"不好...访问链接出错"];
            _UnusualBsView.delegate = self;
            [self.view insertSubview:_UnusualBsView belowSubview:self.addView];
        }else if(status == 0){
            
            _UnusualBsView = [[UnusualBaseView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64) UnusualState:0 AndUnusualTitle:@"不好...连接超时了"];
            _UnusualBsView.delegate = self;
            [self.view insertSubview:_UnusualBsView belowSubview:self.addView];
        }else{
            _UnusualBsView = [[UnusualBaseView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64) UnusualState:OtherStatus AndUnusualTitle:@"其他异常"];
            _UnusualBsView.delegate = self;
            [self.view insertSubview:_UnusualBsView belowSubview:self.addView];
        }

    }];
}
- (void)RefreshBtnClick:(UIButton *)sender{
    
    [_UnusualBsView removeFromSuperview];
    [self.tableview.mj_header beginRefreshing];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SuggesOrComplainCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = UIColorFromRGB(0xf0f0f0);
    cell.delegate = self;
    SugAndComBeanListModel *model = _dataSource[indexPath.row];
    [cell fillCellWithModel:model WithRow:indexPath.row];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    SugAndComBeanListModel *model = _dataSource[indexPath.row];
    SugAndComDetailVC *detailVC = [[SugAndComDetailVC alloc]init];
    if (model.anonymity  == 0) {
        _WhetherName = model.smtPs;
    }else{
        _WhetherName = @"迭名";
    }
    if (model.supportState == 1) {
        _upImage = @"thumb_up_blue";
    }else{
        _upImage = @"thumb_up";
    }
    detailVC.detailData = @{@"title":model.title,@"content":model.suggestion,@"supimage":_upImage,@"supportN":[NSString stringWithFormat:@"赞同数:%ld",model.supportNum],@"pson":[NSString stringWithFormat:@"提交人:%@",_WhetherName],@"branchCom":model.branchName,@"aspectOn":[NSString stringWithFormat:@"%ld",model.aspectOn],@"time":model.time,@"sugTypeID":[NSString stringWithFormat:@"%ld",model.type]};
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (void)AddSuggestion{
    
    SuggestionAndComplainAddVC *addVC = [[SuggestionAndComplainAddVC alloc]init];
    [self.navigationController pushViewController:addVC animated:YES];
}
#pragma mark 封装提示框
- (void)showAlert:(NSString *)Title message:(NSString *)message actionWithTitle:(NSString *)actionWithTitle{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:Title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:actionWithTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
